package Service.Impl;

import Dao.ElderInfoDao;
import Model.Elder;
import Model.ElderInfo;
import Model.ElderInfoChanged;
import Service.ElderInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import utils.Excel;
import utils.ReturnDataForLayui;

import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.*;

@Service("ElderService")
public class ElderInfoServiceImpl implements ElderInfoService {

    @Autowired
    private ElderInfoDao elderInfoDao;
    //  获取全部老人信息
    @Override
    public List<ElderInfo> getAllElderList() {
        System.out.println("service层：查询老人信息");
        return elderInfoDao.getAllElderList();
    }

    //    获取全部变更信息
    @Override
    public List<ElderInfoChanged> getAllElderChangedList(){
        System.out.println("service层：查找老人变更信息");
        return elderInfoDao.getAllElderChangedList();
    }

    //    删除老人信息
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=30000,rollbackFor={RuntimeException.class, Exception.class})
    public String delElder(int id) {
        //1.删除角色对应的权限
        //batchDelRolePerms(id);
        //2.删除角色
        System.out.println("service层：执行删除");
        System.out.println("id:"+id);
        ElderInfo elderInfo=elderInfoDao.findElderInfobyID(id);
        System.out.println("service层:老人的ID："+id);
        System.out.println("service层:存在此老人");
//            记录修改时间
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        //elderInfobyID.setHistory_change_time(timestamp);
        elderInfo.setHistory_change_time(timestamp);
        //System.out.println("修改时间11："+elderInfobyID.getHistory_change_time());
        System.out.println("修改时间22："+elderInfo.getHistory_change_time());
        System.out.println("deparment的内容："+elderInfo);

        int a=elderInfoDao.RecordDel(elderInfo);

        int num=this.elderInfoDao.deleteByPrimaryKey(id);
        if(num<1){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作失败";
        }
        return "ok";
    }

    //  搜索
    @Override
    public List<ElderInfo> findElderInfo(String elderName,String servOrg,String ybID,String personLevel,
                                         String personCatagory,String assessType,String serSituation){
        System.out.println("service层：姓名："+elderName+" ,机构："+servOrg+",医保ID："+ybID+",等级:"+personLevel+
                ",人员性质："+personCatagory+",评估等级："+assessType+",服务状态："+serSituation);
        System.out.println("service层：进入dao层");
        return elderInfoDao.findElderInfo(elderName,servOrg,ybID,personLevel,personCatagory,assessType,serSituation);
    }

    //    根据ID查询
    @Override
    public ElderInfo findElderInfobyID(Integer id){
        return elderInfoDao.findElderInfobyID(id);
    }

    //  搜索-变更页面
    @Override
    public List<ElderInfoChanged> findElderChangedInfo(String nameSearch,String ybidSearch,String titleSearch){
        System.out.println("service层："+nameSearch);
        System.out.println("service层："+ybidSearch);
        System.out.println("service层："+titleSearch);
        System.out.println("service层：进入dao层");
        return elderInfoDao.findElderChangedInfo(nameSearch,ybidSearch,titleSearch);
    }




    //  变更页面-更新信息
    @Override
    public String updateElder(ElderInfo elderInfo, HttpSession session,String settleCode){
        System.out.println("service层:医保ID："+elderInfo.getYbid());
        System.out.println("service层:身份证号："+elderInfo.getId_number());
        if (elderInfo.getId() != null) {
            if(elderInfo.getYbid().toString().length()==6){
                System.out.println("service层:医保ID位数校验正确："+elderInfo.getYbid().toString().length());
                //            根据ID找到修改前的数据
                ElderInfo elderInfobyID=elderInfoDao.findElderInfobyID(elderInfo.getId());
                System.out.println("service层:老人的ID："+elderInfo.getId());
                System.out.println("service层:存在此老人");
//            记录修改时间
                Date date = new Date();
                Timestamp timestamp = new Timestamp(date.getTime());
                elderInfobyID.setHistory_change_time(timestamp);
                elderInfo.setHistory_change_time(timestamp);
                System.out.println("修改时间11："+elderInfobyID.getHistory_change_time());
                System.out.println("修改时间22："+elderInfo.getHistory_change_time());
                System.out.println("deparment的内容："+elderInfo);

//            修改前的数据
                Map<String,Object> oldElder = new HashMap<String,Object>();
                oldElder.put("serv_org",elderInfobyID.getServ_org() );
                oldElder.put("js_id",elderInfobyID.getJs_id() );
                oldElder.put("name", elderInfobyID.getName());
                oldElder.put("gender", elderInfobyID.getGender());
                oldElder.put("person_level", elderInfobyID.getPerson_level());
                oldElder.put("sbcard_id",elderInfobyID.getSbcard_id() );
                oldElder.put("ybid",elderInfobyID.getYbid() );
                oldElder.put("age",elderInfobyID.getAge() );
                oldElder.put("id_number", elderInfobyID.getId_number());
                oldElder.put("person_catagory",elderInfobyID.getPerson_catagory() );
                oldElder.put("phone_number",elderInfobyID.getPhone_number() );
                oldElder.put("contact_people",elderInfobyID.getContact_people());
                oldElder.put("care_assistant",elderInfobyID.getCare_assistant());
                oldElder.put("fwaddress", elderInfobyID.getFwaddress());
                oldElder.put("fwaddresscj", elderInfobyID.getFwaddresscj());
                oldElder.put("fwjz",elderInfobyID.getFwjz());
                oldElder.put("daiyu_start_date",elderInfobyID.getDaiyu_start_date());
                oldElder.put("daiyu_due_date",elderInfobyID.getDaiyu_due_date());
                oldElder.put("ser_situation",elderInfobyID.getSer_situation());
                oldElder.put("assess_type",elderInfobyID.getAssess_type());
                oldElder.put("history_change_time",elderInfobyID.getHistory_change_time());
                oldElder.put("last_serv_org",elderInfobyID.getLast_serv_org());
                System.out.println("service层:旧的数据："+oldElder);

                //            修改后的数据
                Map<String,Object> newElder = new HashMap<String,Object>();
                newElder.put("serv_org",elderInfo.getServ_org());
                newElder.put("js_id",elderInfo.getJs_id() );
                newElder.put("name", elderInfo.getName());
                newElder.put("gender", elderInfo.getGender());
                newElder.put("person_level", elderInfo.getPerson_level());
                newElder.put("sbcard_id",elderInfo.getSbcard_id() );
                newElder.put("ybid",elderInfo.getYbid() );
                newElder.put("age",elderInfo.getAge());
                newElder.put("id_number",elderInfo.getId_number());
                newElder.put("person_catagory",elderInfo.getPerson_catagory() );
                newElder.put("phone_number",elderInfo.getPhone_number() );
                newElder.put("contact_people",elderInfo.getContact_people());
                newElder.put("care_assistant",elderInfo.getCare_assistant());
                newElder.put("fwaddress", elderInfo.getFwaddress());
                newElder.put("fwaddresscj", elderInfo.getFwaddresscj());
                newElder.put("fwjz",elderInfo.getFwjz());
                newElder.put("daiyu_start_date",elderInfo.getDaiyu_start_date());
                newElder.put("daiyu_due_date",elderInfo.getDaiyu_due_date());
                newElder.put("ser_situation",elderInfo.getSer_situation());
                newElder.put("assess_type",elderInfo.getAssess_type());
                newElder.put("history_change_time",elderInfo.getHistory_change_time());
                newElder.put("last_serv_org",elderInfo.getLast_serv_org());
                System.out.println("service层:新的数据："+newElder);


//              比较新旧数据
                for(Map.Entry<String,Object>entry:oldElder.entrySet()){
//                获取当前键值
                    String keyContent=entry.getKey();
                    System.out.println("获取的key值："+keyContent);
//                获取当前键值的value值（新+旧）
                    Object oldValue=entry.getValue() ==null?"":entry.getValue();
                    Object newValue=newElder.get(entry.getKey())==null?"":newElder.get(entry.getKey());
                    System.out.println("比较循环前的数据（旧）："+oldValue);
                    System.out.println("比较循环前的数据（新）："+newValue);
//                比较：如果二者value不同
                    if(!oldValue.equals(newValue)){
                        System.out.println("不同的数据（旧）："+oldValue);
                        System.out.println("不同的数据（新）："+newValue);
                        System.out.println("不同");
//                    建表
                        Map<String,Object> insertInfo = new HashMap<String,Object>();
                        switch (keyContent){
                            case "serv_org": insertInfo.put("changed_title","服务机构");break;
                            case "js_id": insertInfo.put("changed_title","结算代码");break;
                            case "name":insertInfo.put("changed_title","姓名");break;
                            case "gender":insertInfo.put("changed_title","性别");break;
                            case "person_level":insertInfo.put("changed_title","等级");break;
                            case "sbcard_id":insertInfo.put("changed_title","社保卡ID");break;
                            case "ybid":insertInfo.put("changed_title","医保ID");break;
                            case "age":insertInfo.put("changed_title","年龄");break;
                            case "id_number":insertInfo.put("changed_title","身份证号");break;
                            case "person_catagory":insertInfo.put("changed_title","人员性质");break;
                            case "phone_number": insertInfo.put("changed_title","联系电话");break;
                            case "contact_people": insertInfo.put("changed_title","联系人");break;
                            case "care_assistant":insertInfo.put("changed_title","护工");break;
                            case "fwaddress":insertInfo.put("changed_title","接受服务地址");break;
                            case "fwaddresscj":insertInfo.put("changed_title","接受服务地址所在街镇");break;
                            case "fwjz":insertInfo.put("changed_title","接受服务地址所在村居");break;
                            case "daiyu_start_date":insertInfo.put("changed_title","待遇起始日");break;
                            case "daiyu_due_date":insertInfo.put("changed_title","待遇到期日");break;
                            case "ser_situation":insertInfo.put("changed_title","服务状态");break;
                            case "assess_type":insertInfo.put("changed_title","评估类型");break;
                            case "last_serv_org":insertInfo.put("changed_title","上一家护理机构");break;
                        }
                        insertInfo.put("name", elderInfo.getName());
                        insertInfo.put("ybid", elderInfo.getYbid());
                        insertInfo.put("history_change_time", elderInfo.getHistory_change_time());
                        insertInfo.put("new_content", newValue);
                        insertInfo.put("start_change_date",elderInfo.getStart_change_date());
                        insertInfo.put("history_content", oldValue);
                        insertInfo.put("settlement_code",settleCode);
                        System.out.println("变更后的表："+insertInfo);
                        System.out.println("进入dao层：InsertHistoryChange");
//                    以哈希表形式传入更改后的数据
                        this.elderInfoDao.InsertHistoryChange(insertInfo);
                    }else{
//                    若value相同，则不传
                        System.out.println("相同的数据（旧）："+oldValue);
                        System.out.println("相同的数据（新）："+newValue);
                        System.out.println("相同");
                    }
                }
                this.elderInfoDao.updatebyID(elderInfo);
                System.out.println("update成功（Impl）");
            }else{
                System.out.println("校验失败：医保ID的长度为："+elderInfo.getYbid().toString().length());
                return "errorSettleCode";
            }
        }
        return "ok";
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    @Override
    public ReturnDataForLayui getList(ElderInfo elderInfo) {
        PageHelper.startPage(elderInfo.getPage(),elderInfo.getLimit());
        List<ElderInfo> list = elderInfoDao.getList(elderInfo);
        PageInfo<ElderInfo> info = new PageInfo<>(list);
        return ReturnDataForLayui.success(list,info.getTotal());
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    @Override
    public ReturnDataForLayui getList2(ElderInfo elderInfo) {
        PageHelper.startPage(elderInfo.getPage(),elderInfo.getLimit());
        List<ElderInfo> list = elderInfoDao.getList2(elderInfo);
        PageInfo<ElderInfo> info = new PageInfo<>(list);
        return ReturnDataForLayui.success(list,info.getTotal());
    }

    //  传入excel
    @Override
    public String InputExcel(InputStream is, String originalFilename,String settleCode) {
        System.out.println("service层：传入excel文件");
        Map<String,Map<String,Object>> param = new HashMap<String,Map<String,Object>>();
        Map<String,Object> ginsengMap = new HashMap<String,Object>();
        List<ArrayList<Object>> list;
        if (originalFilename.endsWith(".xls")) {
            System.out.println("service层：是2003版的excel");
            list = Excel.readExcel2003(is);
        } else {
            System.out.println("service层：是2007版的excel");
            list = Excel.readExcel2007(is);
        }
        for (int i=0,j=list.size();i<j;i++){
            List<Object> row = list.get(i);
            System.out.println("service层：当前i= "+i);
            System.out.println("service层：当前row= "+row);
            System.out.println("service层：判断人员状态： "+row.get(19).toString());
//            ginsengMap.put("id", row.get(0).toString());;
            if(row.get(19).toString().equals("无效转出")){
                System.out.println("service层：人员状态为无效转出");
                ginsengMap.put("serv_org", row.get(1).toString());
                ginsengMap.put("name", row.get(2).toString());
                ginsengMap.put("gender", row.get(3).toString());
                ginsengMap.put("person_level", row.get(4).toString());
                ginsengMap.put("sbcard_id", row.get(5).toString());
                ginsengMap.put("ybid", row.get(6).toString());
                ginsengMap.put("age", row.get(7).toString());
                ginsengMap.put("id_number", row.get(8).toString());
                ginsengMap.put("person_catagory", row.get(9).toString());
                ginsengMap.put("phone_number", row.get(10).toString());
                ginsengMap.put("contact_people", row.get(11).toString());
                ginsengMap.put("care_assistant", row.get(12).toString());
                ginsengMap.put("fwaddress", row.get(13).toString());
                ginsengMap.put("fwaddresscj", row.get(14).toString());
                ginsengMap.put("fwjz", row.get(15).toString());
                ginsengMap.put("daiyu_start_date", row.get(16).toString());
                ginsengMap.put("daiyu_due_date", row.get(17).toString());
                ginsengMap.put("ser_situation", row.get(18).toString());
                ginsengMap.put("assess_type", row.get(19).toString());
                ginsengMap.put("last_serv_org", row.get(20).toString());
                ginsengMap.put("js_id",settleCode);
                param.put("keys", ginsengMap);
                elderInfoDao.InputExcel(param);
                System.out.println("service层：inputExcel成功");
            }
            else{
                System.out.println("service层：人员状态非无效转出");
            }
        }
        return "01";
    }

    //    派工单页面：查询要被服务的老人
    @Override
    public List<ElderInfo> searchArrangeElder(String elderName,String Ybid,String ID){
        System.out.println("service层："+elderName);
        System.out.println("service层："+Ybid);
        System.out.println("service层："+ID);
        System.out.println("service层：进入dao层");
        return elderInfoDao.searchArrangeElder(elderName,Ybid,ID);
    }


    //新增派工订单页面：搜索老人
    @Override
    public List<ElderInfo> findElderInfobyYbid(String elderYbid){
        System.out.println("service层/findElderInfobyYbid:"+elderYbid);
        return elderInfoDao.findElderInfobyYbid(elderYbid);

    }

    /**
     * 获取老人的ID和name字段
     */
    @Override
    public List<ElderInfo> getLrIdName(){
        List<ElderInfo> list = elderInfoDao.getLrIdName();
        System.out.println("[获取到老人的ID和name：]"+list);
        return list;
    }

    @Override
    public List<ElderInfo> getLrNameByCode(String settlement_code){
        List<ElderInfo> list = elderInfoDao.getLrNameByCode(settlement_code);
        System.out.println("[根据机构查询老人姓名：]"+list);
        return list;
    }

    @Override
    public List<ElderInfo> getLrIdNumberByName(String name){
        List<ElderInfo> list = elderInfoDao.getLrIdNumberByName(name);
        System.out.println("[根据姓名查询老人身份证：]"+list);
        return list;
    }

    @Override
    public void updateLrDevice(ElderInfo elderInfo){
        elderInfoDao.updateLrDevice(elderInfo);
        System.out.println("[同步老人的发放设备！]");
    }

//     * 老人页面添加权限:显示机构名下老人
    @Override
    public List<ElderInfo> getElderbySettleCode(String settleCode){
        System.out.println("service层:机构结算ID："+settleCode);
        return elderInfoDao.getElderbySettleCode(settleCode);
    }

//     * 老人变更页面添加权限:显示机构名下老人
    @Override
    public List<ElderInfoChanged> getAllElderChangedsbySettleCode(String settleCode){
        return elderInfoDao.getAllElderChangedsbySettleCode(settleCode);
    }
//     * 老人信息页面添加权限:搜索机构名下老人
    @Override
    public List<ElderInfo> findElderInfobySettleCode(String elderName,String servOrg,String ybID,String personLevel,
                                                     String personCatagory,String assessType,String serSituation,String settleCode){
        return elderInfoDao.findElderInfobySettleCode(elderName,servOrg,ybID,personLevel,personCatagory,assessType,serSituation,settleCode);
    }


//     * 搜索/变更页面
    @Override
    public List<ElderInfoChanged> findElderInfoChangedsbySettleCode(String nameSearch,String ybidSearch,String titleSearch,String settleCode){
        return elderInfoDao.findElderInfoChangedsbySettleCode(nameSearch,ybidSearch,titleSearch,settleCode);
    }

    // 新增订单页面：搜索机构名下的老人
    @Override
    public  List<ElderInfo> searchArrangeElderbySettleCode(String elderName,String Ybid,String ID,String SettleCode){
        return elderInfoDao.searchArrangeElderbySettleCode(elderName,Ybid,ID,SettleCode);
    }

    // 根据老人的信标Id查找姓名和医保Id
    @Override
    public List<ElderInfo> findNameByDeviceLr(String device_lr){
        return elderInfoDao.findNameByDeviceLr(device_lr);
    }
}
